﻿namespace GalaxyEngine.Ui
{
    using System.Collections.Generic;
    using System.Web.Mvc;
    using System.Web;
    using System.IO;

    public sealed class MasterPage : IHtmlObject
    {
        private Doctype doctype;
        private HttpServerUtility server;
        public List<UserControl> UserControls { get; set; }

        public MasterPage(Doctype doctype) : base()
        {
            this.UserControls = new List<UserControl>();
            this.doctype = doctype;
            this.server = HttpContext.Current.Server;
        }
        
        public MvcHtmlString ToMvcHtmlString() 
        {
            return MvcHtmlString.Create(RenderHtml());
        }

        public string RenderHtml()
        {
            TagBuilder builderHtml = new TagBuilder(Resources.Html);
            TagBuilder builderHead = new TagBuilder(Resources.Head);
            TagBuilder builderBody = new TagBuilder(Resources.Body);
            string dojo = "http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js";
            builderHead.InnerHtml = string.Format(Resources.DefaultScript, dojo);
            string theme = "http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dijit/themes/claro/claro.css";
            builderHead.InnerHtml += string.Format(Resources.DefaultCss, theme);
            builderBody.MergeAttribute("class", "claro");

            foreach (UserControl userControl in UserControls)
            {
                foreach (IWidget widget in userControl.Widgets)
                {
                    builderHead.InnerHtml += widget.GetScript();
                    builderHead.InnerHtml += widget.GetStyle();
                }

                builderBody.InnerHtml += userControl.RenderHtml();
            }

            builderHtml.InnerHtml += builderHead.ToString(TagRenderMode.Normal);
            builderHtml.InnerHtml += builderBody.ToString(TagRenderMode.Normal);
            string result = Resources.DoctypeHtmlFive + builderHtml.ToString(TagRenderMode.Normal);
            return result;
        }
    }
}
